package com.company.pangu.ip2region.client;

import cn.hutool.http.HttpUtil;
import com.company.pangu.ip2region.config.Ip2RegionConfig;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbMakerConfigException;
import org.lionsoul.ip2region.DbSearcher;

import java.util.Objects;

/**
 * <p>ip2region client</p >
 * https://github.com/lionsoul2014/ip2region
 *
 * @author youyoukele
 * @version 1.0
 * @date 2021/8/31
 */
@Slf4j
public class Ip2RegionClient {

    private static final String NONE = "0";

    private DbSearcher searcher;

    public Ip2RegionClient(Ip2RegionConfig ip2RegionConfig) {
        try {
            DbConfig config = new DbConfig();
            this.searcher = new DbSearcher(config, HttpUtil.downloadBytes(ip2RegionConfig.getDbUrl()));
        } catch (DbMakerConfigException e) {
            log.error("init ip2region error", e);
        }
    }

    /**
     * 国家|区域|省份|城市|ISP_
     * 中国|0|上海|上海|电信
     * 中国|0|香港|0|电讯盈科
     * 中国|0|台湾|0|中华电信
     *
     * @param ip
     * @return 若没解析到ip，会返回 "NONE" ["0"]
     */
    public String memorySearchCity(String ip) {
        if (Objects.isNull(searcher)) {
            return NONE;
        }
        try {
            DataBlock dataBlock = searcher.memorySearch(ip);
            if (Objects.isNull(dataBlock)) {
                return NONE;
            }
            String[] regions = dataBlock.getRegion().split("\\|");
            if (NONE.equals(regions[3])) {
                return regions[2];
            }
            return regions[3];
        } catch (Exception e) {
            log.error("memory search city has error");
        }
        return NONE;
    }

    @SneakyThrows
    public void shutdown() {
        if (Objects.nonNull(searcher)) {
            searcher.close();
        }
    }

}